﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace NDownloader
{
    public static class SaveFromURL
    {
        public static void Save(string strSourceURL, List<String> strArrLinks, string strSavePath, string strProjectName)
        {
            string strSavePathProject = System.IO.Path.Combine(strSavePath, strProjectName);
            if (System.IO.Directory.Exists(strSavePathProject) == false)
            {
                System.IO.Directory.CreateDirectory(strSavePathProject);
            }
            
            int intCounter = 0;
            foreach (string strFileLink in strArrLinks)
            {

                try
                {
                    // assignment operators (=) invalid in a foreach loop so we need a new variable.

                    string strFileLinkURL = strFileLink;

                    //check if the link is a relative path and we need to add the first part of the URL

                    if (strFileLinkURL.Contains("://") == false)
                    {
                        strFileLinkURL = System.IO.Path.Combine(strSourceURL, strFileLink);
                    }


                    Uri uriLink = new Uri(strFileLinkURL);
                    string strFileName = System.IO.Path.GetFileName(uriLink.LocalPath);

                    Debug.WriteLine(strFileLinkURL);

                    if (System.IO.File.Exists(System.IO.Path.Combine(strSavePath, strProjectName, strFileName)) == false)
                    {
                        intCounter += 1;
                        Debug.WriteLine(intCounter.ToString() + " " + strFileName);
                        Console.WriteLine(intCounter.ToString() + " " + strFileName);

                        string strFileFullPath = System.IO.Path.Combine(strSavePath, strProjectName, strFileName);
                        System.Net.WebClient wc = new System.Net.WebClient();
                        wc.DownloadFile(strFileLinkURL, strFileFullPath);
                    }
                }

                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    }
}